const {
  toUrl,
  globalData,
  msgLoading
} = getApp();
import {
  request
} from "@/utils/request";
Page({
  toUrl,
  data: {
    globalData,
    typeObj: null,
    detail: null,
    coupons: null,
    orderSn: null,
    pageNum: 0,
    isPay: false,
    isBack: false,
    id: null,
    isTrue:false,
    isShow:false,
    quota_num:0
  },
  getPageNum(num) {
    const page = getCurrentPages()
    if (page.length > 2) {
      const len = page.length - 1 - num
      if (page[len].route == 'pages/order/form') {
        // console.log('+1')
        this.setData({
          pageNum: this.data.pageNum + 1
        })
        this.getPageNum(num + 1)
      }
    } else {
      this.setData({
        pageNum: 1
      })
    }
    console.log(this.data.pageNum)
  },
  goback() {
    wx.navigateBack({
      delta: 1,
    })
  },
  //增加商品数量
  plus(e) {
    if (this.data.quota_num == this.data.typeObj?.num) {
      console.log('符合');
      wx.showToast({
        title: `限购${this.data.typeObj?.num}个`,
        icon:'none'
      })
      return
    }

     if (this.data.isTrue == true) {
       return
     }
    if (this.data.detail.info.is_voucher == 1) {
      wx.showToast({
        title: '该商品属于优惠券商品,数量限购一个',
        icon:'none'
      })
      return
    }    
    if (this.data.typeObj == null) {
      this.setData({
        'typeObj.num':1
      })
    }
    let typeObj = {
      ...this.data.typeObj
    };
    typeObj.num = Number(typeObj.num) + 1;
    // console.log(this.data.typeObj);
    this.setData({
      typeObj: typeObj,
    isTrue: true

    });
    setTimeout(() => {
  
      this.setData({
        isTrue :false
      })
    }, 1000);
    this.getCartOrder().then(() => {
1
    }).catch((err) => {

      typeObj.num = Number(typeObj.num) - 1;

      this.setData({
        typeObj: typeObj,
      });
    })
  },
  //减少商品数量
  del(e) {
    const typeObj = this.data.typeObj;
    if (typeObj.num == 1) {
      return;
    }
    typeObj.num = Number(typeObj.num) - 1;
    this.setData({
      typeObj: typeObj,
    });
    this.getCartOrder()
  },
  //获取购物车订单
  getCartOrder() {
    const that = this;
    const data = {
      id: this.data.id,
      num: this.data.typeObj == null ? 1 : this.data.typeObj.num ,
      act: ''
    };
    return request("seckill/addorder", {
      data
    }).then((res) => {
      const list = res.data
    
      const {
        goods
      } = list
      // goods.forEach(item => {
      //   item.image = globalData.baseUrl + item.image
      // })
      that.setData({
        detail: list,
        isShow:true
        // 'typeObj.num': 1
      });
    }).catch((err)=>{
      typeObj.num = Number(typeObj.num) - 1;
      this.setData({
        typeObj: typeObj,
      });
      // wx.navigateBack()
    }).finally(()=>{
      setTimeout(() => {
       wx.hideLoading()
      }, 1000);
      wx.stopPullDownRefresh()

      // this.setData({
      //   isShow:true
      // })
    })
  },
  //获取直接购买订单
  getBuyOrder() {
    const that = this;
    const data = {
      typeid: 1,
      coupon_id: this.data.coupons ? this.data.coupons.coupon_id : 0,
      goods_id: this.data.typeObj.goods_id,
      num: this.data.typeObj.num,
    };
    if (this.data.typeObj.item_id) {
      data.item_id = this.data.typeObj.item_id;
    }
    return request("cart/addorder", {
      data
    }).then((res) => {
      const list = res.data
      const {
        goods
      } = list
      goods.forEach(item => {
        item.image = globalData.baseUrl + item.image
      })
      that.setData({
        detail: list,
      });
    })
  },
  //获取优惠券页面
  getTicket() {
    wx.redirectTo({
      url: "/pages/order/ticket/ticket?obj=" + JSON.stringify(this.data.typeObj),
    });
  },
  //提交订单
  submit() {
    if (this.data.typeObj == null) {
      this.setData({
        'typeObj.num':1
      })
    }
    const that = this
    const data = {
      id: this.data.id,
      num: this.data.typeObj.num,
      act: "submit",
    };
    let url = 'seckill/addorder'
    request(url, {
      data
    }).then((res) => {
      const {
        order_sn
      } = res.data;
      that.setData({
        orderSn: order_sn
      })
      const data = {
        order_sn: order_sn,
      };
      if (res.data.pay_status == 1) {
        wx.showToast({
          title: res.message,
        })
        that.setData({
          isPay: true
        })
        wx.redirectTo({
          url: '../order/status/status?order_sn=' + res.data.order_sn,
          // url: './status/status?order_sn=' + res.data.order_sn,
        })
      } else {
        wx.showLoading({
          title: '加载中...',
          icon:'none',
          mask:true,
        })
        request("payment/pay", {
          data
        }).then((res) => {
          wx.requestPayment({
            appId: res.data.appId,
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success: function (res) {
          
              if (res.errMsg == 'requestPayment:ok') {
                that.setData({
                  isPay: true
                })
                wx.redirectTo({
                  url: '../order/status/status?order_sn=' + that.data.orderSn,
                  // url: './status/status?order_sn=' + that.data.orderSn,
                })
              }
              wx.hideLoading()
            },fail:function(err){
              if (err.errMsg == 'requestPayment:fail cancel') {
                that.getCancel()
              }
              wx.hideLoading()

            }
          });
        });
      }

    });
  },
  getCancel(){
    let data = {
      order_sn:this.data.orderSn
    }
    return request("order/cancel", {
      data
    }).then((res) => {
      console.log('取消成功');
      // this.setData({
      //   detail: res.data,
      // });
    });
  },
  getRepurchase(order_id) {
    let data = {
      order_id: this.data.typeObj.order_id,
      coupon_id: this.data.coupons ? this.data.coupons.coupon_id : 0,
    };
    return request("cart/againorder", {
      data
    }).then((res) => {
      this.setData({
        detail: res.data,
      });
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.showLoading({
      title: '加载中...',
      icon:'none',
      mask:true,
    })

    let {
      id,quota_num
    } = options
 
    this.setData({
      id: id,
      quota_num:quota_num
    });
    this.getCartOrder()
    // if (options.type === "cart") {
    // this.setData({
    //   typeObj: options,
    // });
    // //获取购物车
    // this.getCartOrder().then(() => {
    //   if (options.coupons_id) {
    //     const obj = this.data.detail.coupons.find((item) => {
    //       return item.coupon_id == options.coupons_id;
    //     });
    //     this.setData({
    //       coupons: obj,
    //     });
    //     this.getCartOrder();
    //   }
    // });
    // }
    // if (options.type === "buy") {
    //   this.setData({
    //     typeObj: options,
    //   });
    //   this.getBuyOrder().then(() => {
    //     if (options.coupons_id) {
    //       const obj = this.data.detail.coupons.find((item) => {
    //         return item.coupon_id == options.coupons_id;
    //       });
    //       this.setData({
    //         coupons: obj,
    //       });
    //       this.getBuyOrder();
    //     }
    //   });
    // }
    // if (options.type === "repurchase") {
    //   this.setData({
    //     typeObj: options,
    //   });
    //   //再来一单
    //   this.getRepurchase().then(() => {
    //     if (options.coupons_id) {
    //       const obj = this.data.detail.coupons.find((item) => {
    //         return item.coupon_id == options.coupons_id;
    //       });
    //       this.setData({
    //         coupons: obj,
    //       });
    //       this.getRepurchase();
    //     }
    //   });

    //   // let { order_id } = options;
    //   // this.getRepurchase(order_id);
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const page = getCurrentPages()
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.isPay) {
      wx.redirectTo({
        url: './status/status?order_sn=' + this.data.orderSn,
      })
    }
    // else if(!this.data.isBack) {
    //   const page = getCurrentPages()
    //   let pageNum = 0
    //   let isPlus = true
    //   for(let i = page.length-1; i > 0; --i) {
    //     if(page[i].route == 'pages/order/form') {
    //       if(isPlus) {
    //         pageNum++
    //       }
    //     }else {
    //       isPlus = false
    //     }
    //   }
    //   wx.navigateBack((pageNum - 1))
    // }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    msgLoading()
    this.getCartOrder()

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});